import axios from "axios";
import router from "@/router";
import { Message } from "element-ui";
import { localClear } from "@/util/util";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });

// export const appBaseUrl =
//   process.env.VUE_APP_ENV === "local" ? "api/" : process.env.VUE_APP_BASE_URL;

export const appBaseUrl =
  process.env.VUE_APP_BASE_URL

const http = axios.create({
  timeout: 20000,
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded',
    "Content-Type": "application/json",
  },
});
  
http.interceptors.request.use(
  (config) => {
    NProgress.start();
    const _config = config;
    _config.url = appBaseUrl + _config.url;
    if (_config.url.indexOf("login") === -1) {
      // console.log('localStorage.getItem("token")',localStorage.getItem("token"))
      _config.headers = {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      };
    }
    return _config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  (response) => {
    NProgress.done();
    if (response.data.code === 200) {
      return response.data.data;
    } else if (response.data.code === 10007 || response.data.code === 10008) {
      Message.closeAll();
      Message.error("登陆信息过期，请重新登陆");
      localClear();
      router.replace("/login");
    } else {
      Message.error(response.data.msg);
      return Promise.reject(response.data);
    }
  },
  (error) => {
    console.log(error.response);
    Message.error("服务器错误");
    NProgress.done();
    return Promise.reject(error);
  }
);

http.get = (url) => {
  return http({
    method: "get",
    url,
  });
};

http.post = (url, data) => {
  return http({
    method: "post",
    url,
    data,
  });
};

export default http;
